package com.heima.wemedia.service.impl;

import apis.article.IArticleClient;
import apis.user.IUserClient;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.heima.common.constants.WemediaConstants;
import com.heima.model.article.dtos.ApArticleCommentDto;
import com.heima.model.article.dtos.ApArticleLikeDto;
import com.heima.model.article.dtos.ApArticleListDto;
import com.heima.model.article.dtos.ApArticleOpenCommentDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.ManagerCommentPageDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.ThreadLocalUtil;
import com.heima.verify.service.impl.VerifyMaterialServiceImpl;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.pojos.ApComment;
import com.heima.wemedia.pojos.ApCommentLike;
import com.heima.wemedia.pojos.ApCommentRepay;
import com.heima.wemedia.pojos.ApCommentRepayLike;
import com.heima.wemedia.pojos.vos.CommentRepayListVo;
import com.heima.wemedia.service.WmCommentManageService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmCommentManageServiceImpl implements WmCommentManageService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmUserMapper wmUserMapper;


    /**
     * 查询自媒体端文章的评论统计数据
     *
     * @param pageDto
     * @return
     */
    @Override
    public ResponseResult findNewsComments(ManagerCommentPageDto pageDto) {

        pageDto.checkParam();

        Integer userId = ThreadLocalUtil.get();
        ApArticleCommentDto dto = new ApArticleCommentDto();
        dto.setBeginDate(pageDto.getBeginDate());
        dto.setEndDate(pageDto.getEndDate());
        dto.setWmUserId(userId);
        dto.setPage(pageDto.getPage());
        dto.setSize(pageDto.getSize());

        return  articleClient.findArticleComment(dto);
    }

    /**
     * 开启或关闭评论
     *
     * @param openDto
     * @return
     */
    @Override
    public ResponseResult toOpenComment(ApArticleOpenCommentDto openDto) {
        if (openDto==null||openDto.getArticleId()==null||openDto.getOperation()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //app端用户id
        WmUser dbUser = wmUserMapper.selectById( ThreadLocalUtil.get());
        Integer apUserId = dbUser.getApUserId();

        //清空该文章的所有评论
        List<ApComment> apCommentList = mongoTemplate
                .find(Query.query(Criteria.where("entryId")
                        .is(openDto.getArticleId()).and("authorId").is(apUserId)), ApComment.class);
        for (ApComment apComment : apCommentList) {
            List<ApCommentRepay> commentRepayList = mongoTemplate.find(Query.query(Criteria.where("commentId")
                    .is(apComment.getId())
                    .and("authorId").is(apUserId)), ApCommentRepay.class);
            List<Long> commentRepayIdList = commentRepayList.stream().map(ApCommentRepay::getId).distinct().collect(Collectors.toList());
            //删除所有的评论回复点赞数据
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").in(commentRepayIdList).and("authorId").is(apUserId)), ApCommentRepayLike.class);

            //删除该评论的所有的回复内容
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId)), ApCommentRepay.class);

            //删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId)), ApCommentLike.class);

        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(openDto.getArticleId()).and("authorId").is(apUserId)),ApComment.class);

        //修改app文章的config配置
        return articleClient.openComment(openDto);
    }

    /**
     * 查看文章的详细评论信息
     *
     * @param listDto
     * @return
     */
    @Override
    public ResponseResult toListComment(ApArticleListDto listDto) {
        listDto.checkParam();

        if (listDto==null||listDto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //评论列表
        List<CommentRepayListVo> commentRepayListVoList = new ArrayList<>();

        /**
         * 每个人的评论
         */
        Query query = Query.query(Criteria.where("entryId").is(listDto.getArticleId()));
        //设置起始数
        query.skip((listDto.getPage() - 1) * listDto.getSize());
        //设置查询条数
        query.limit(listDto.getSize());

//                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
//        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

//        Query query = Query.query(Criteria.where("entryId").is(listDto.getArticleId()));
//        Pageable pageable =  PageRequest.of(listDto.getPage(),listDto.getSize());
//        query.with(pageable);
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        System.out.println(list);
        /*每个人的评论加上回复*/
        for (ApComment apComment : list) {
            CommentRepayListVo vo = new CommentRepayListVo();
            vo.setApComments(apComment);
            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId()))
                                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);
            vo.setApCommentRepays(apCommentRepays);

            /*添加到评论列表*/
            commentRepayListVoList.add(vo);
        }

        return ResponseResult.okResult(commentRepayListVoList);
    }

    @Autowired
    private VerifyMaterialServiceImpl verifyMaterialService;

    @Autowired
    private IUserClient userClient;
    /**
     * 回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getContent().length() > 140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字");
        }

        //2.安全检查
        Map map = verifyMaterialService.VerifyText(dto.getContent());
        Integer type = (Integer) map.get("conclusionType");
        try {
            if (type == WemediaConstants.WM_CHECK_MAYBE || type == WemediaConstants.WM_CHECK_UNKNOWN) {
                return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_AUDIT_NOT_ALLOW);
            } else if (type == WemediaConstants.WM_CHECK_FORBID) {
               return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_AUDIT_NOT_ALLOW);
            }
        } catch (Exception e) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CONTENT_AUDIT_NOT_ALLOW);
        }

        //获取自媒体人信息
        WmUser dbUser = wmUserMapper.selectById(ThreadLocalUtil.get());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取app端用户信息
        Integer userId = dbUser.getApUserId();
        ApUser apUser = userClient.getUser(userId).getData();
        //3.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        apCommentRepay.setId(IdWorker.getId());
        mongoTemplate.save(apCommentRepay);

        //5更新回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult toLikeComment(ApArticleLikeDto dto) {
        //1.检查参数
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);


        WmUser dbUser = wmUserMapper.selectById(ThreadLocalUtil.get());
        if(dbUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //获取app端用户信息
        ApUser apUser = userClient.getUser(dbUser.getApUserId()).getData();

        Query query1 = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(dto.getCommentId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        if (apCommentLikes!=null||apCommentLikes.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }

        //3.点赞
        if (apComment != null && dto.getOperation() == 0) {
            //更新评论点赞数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //保存评论点赞数据
            ApCommentLike apCommentLike = new ApCommentLike();
           /* long id = IdWorker.getId();
            apCommentLike.setId(id);*/
            apCommentLike.setId(IdWorker.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setAuthorId(apUser.getId());
            mongoTemplate.save(apCommentLike);
        } else {
            //更新评论点赞数量
            int tmp = apComment.getLikes() - 1;
            tmp = tmp < 1 ? 0 : tmp;
            apComment.setLikes(tmp);
            mongoTemplate.save(apComment);

            //删除评论点赞
            Query query = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUser.getId()));
            mongoTemplate.remove(query, ApCommentLike.class);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("likes", apComment.getLikes());
        return ResponseResult.okResult(result);
    }

    /**
     * 删除评论
     *
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult delComment(Long commentId) {
        if(commentId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论id为空");
        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)),ApComment.class);
        //删除该评论的所有的回复内容
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)),ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除评论回复
     *
     * @param commentRepayId
     * @return
     */
    @Override
    public ResponseResult delCommentRepay(Long commentRepayId) {
        if(commentRepayId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论回复id为空");
        }
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentRepayId)),ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
